import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';

import { Observable, Subject } from 'rxjs';

import { HeroSearchService } from '../shared/hero-search.service';
import { HeroService } from '../shared/hero.service';
import { Hero } from '../shared/hero.model';

@Component({
    selector: 'hero-search',
    templateUrl: './hero-search.component.html',
    styleUrls: ['./hero-search.component.css'],
    providers: [HeroSearchService]
})
export class HeroSearchComponent implements OnInit {
    heroes$: Observable<Hero[]>;
    private searchTerms = new Subject<string>();

    constructor(
        private heroService: HeroService,
        private heroSearchSerive: HeroSearchService,
        private router: Router
    ) { }

    ngOnInit(): void {
        // this.heroes = this.searchTerms
        //     .debounceTime(300)              // wait 300ms after each keystroke before considering the term
        //     .distinctUntilChanged()         // ignore if next search term is same as previous
        //     .switchMap(term => term ? this.heroSearchSerive.search(term) : Observable.of<Hero[]>([]))
        //     .catch(error => {
        //         console.log(error);
        //         return Observable.of<Hero[]>([]);
        //     });
    }

    trackByHeroes = this.heroService.trackByHeroes;

    // Push a search term into the observable stream.
    search(term: string): void {
        this.searchTerms.next(term);
    }

    gotoDetail(hero: Hero): void {
        let link = ['/heroes/detail', hero.id];
        this.router.navigate(link);
    }
}